package cn.zzu.Etrip.localbest.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.example.administrator.etrip.MainActivity;
import com.example.administrator.etrip.R;
import java.util.ArrayList;
import java.util.HashMap;
import cn.zzu.Etrip.localbest.service.LocalBestService;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
 * Created by ASUS on 2018/5/23.
 */

public class LocalBestActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener{
    private ViewPager viewPager;//主要功能是用来左右滑动的
    private int[] imageResIds;
    private ArrayList<ImageView> imageViewList;
    private LinearLayout ll_point_container;
    private String[] contentDescs;
    private TextView tv_desc;
    private int previousSelectedPosition = 0;
    boolean isRunning = false;
    //*********************************************************
    private ListView listView;
    private Button buttonbendi, buttonzhoubian, buttonyuanfang;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.localbest);
        //定义一个动态的数组
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

        listView = findViewById(R.id.localbest_listView);
        buttonbendi = findViewById(R.id.bendi);
        buttonzhoubian = findViewById(R.id.zhuobian);
        buttonyuanfang = findViewById(R.id.yuanfang);

        //为每一个按钮添加一个监听器
        buttonbendi.setOnClickListener(new ButtonListener(R.id.bendi, list, listView,LocalBestService.bendiimageId));
        buttonzhoubian.setOnClickListener(new ButtonListener(R.id.zhuobian, list, listView,LocalBestService.zhuobianImageId));
        buttonyuanfang.setOnClickListener(new ButtonListener(R.id.yuanfang, list, listView,LocalBestService.dangjiImageId));

        //建立适配器
        for (int i = 0; i < 5; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemImage", LocalBestService.bendiimageId[i]);
            map.put("ItemTitle", LocalBestService.bendiimageInfo[i]);
            list.add(map);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(LocalBestActivity
                .this, list, R.layout.layout_listview_item, new String[]{"ItemImage", "ItemTitle"}, new int[]{R.id.localbest_ItemImage, R.id.localbest_ItemText});
        listView.setAdapter(simpleAdapter);
        //为listView绑定一个适配器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.localBestPayActivity");
                Bundle bundle = new Bundle();
                bundle.putInt("id",LocalBestService.bendiimageId[position]);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        //加载轮播图*************************************************
        // 初始化布局 View视图
        initViews();

        // Model数据
        initData();

        // Controller 控制器
        initAdapter();

        //轮播图的主要功能就是开启一个线程！ 开启轮询
        new Thread() {
            public void run() {
                isRunning = true;
                while (isRunning) {
                    try {

                        //定义一个线程，控制轮播图的轮播时间
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 往下跳一位
                    ///*********Runnable方法功能，如果当前线程是UI线程就会立即执行，如果不是的话会发布到UI事件队列等待
                    runOnUiThread(new Runnable() {

                        public void run() {
                            System.out.println("设置当前位置: " + viewPager.getCurrentItem());
                            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                        }
                    });
                }
            }

//线程的正式开启
        }.start();

    }

    //定义按钮组监听器
    class ButtonListener implements View.OnClickListener {
        private int a;
        private ArrayList<HashMap<String, Object>> list;
        private ListView listView;
        private int []imageid;
     ///构造方法给以上参数进行赋值
        public ButtonListener(int a, ArrayList<HashMap<String, Object>> list, ListView listView,int []imageid) {
            this.a = a;
            this.list = list;
            this.listView = listView;
            this.imageid=imageid;
        }

        public void onClick(View v) {
            switch (a) {
                case R.id.bendi:
                    setAdapter(imageid, LocalBestService.bendiimageInfo, listView);
                    break;
                case R.id.zhuobian:
                    setAdapter(imageid, LocalBestService.bendiimageInfo, listView);
                    break;
                case R.id.yuanfang:
                    setAdapter(imageid, LocalBestService.bendiimageInfo, listView);
                    break;
            }
        }

        public void setAdapter(int[] imageId, String[] imageInfo, ListView listView) {

            //主要的代码，将以前的 数据进行清除，然后在添加新的内容***************************************************
            list.clear();
            for (int i = 0; i < 5; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("ItemImage", imageId[i]);
                map.put("ItemTitle", imageInfo[i]);
                list.add(map);
            }
            //建立一个适配器
            SimpleAdapter simpleAdapter2;
            simpleAdapter2 = new SimpleAdapter(LocalBestActivity
                    .this, list, R.layout.layout_listview_item, new String[]{"ItemImage", "ItemTitle"}, new int[]{R.id.localbest_ItemImage, R.id.localbest_ItemText});
            listView.setAdapter(simpleAdapter2);
            //为listView绑定一个适配器
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                   Intent intent = new Intent();
                    intent.setAction("android.intent.action.localBestPayActivity");
                    Bundle bundle = new Bundle();
                    bundle.putInt("id",imageid[position]);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
        }

    }
    //**************************************
    protected void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }

    private void initViews() {
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setOnPageChangeListener(this);// 设置页面更新监听
//      viewPager.setOffscreenPageLimit(1);// 左右各保留几个对象
        ll_point_container = (LinearLayout) findViewById(R.id.ll_point_container);

        tv_desc = (TextView) findViewById(R.id.tv_desc);

    }
    /**
     * 初始化要显示的数据
     */
    private void initData() {
        // 图片资源id数组.*******放置在viewPaper之中
        imageResIds = new int[]{R.mipmap.localbest_lunbo_md_01, R.mipmap.localbest_lunbo_md_02, R.mipmap.localbest_lunbo_md_03, R.mipmap.oneday_sm_fangte04, R.mipmap.oneday_sm_fangte03};
        // 文本描述
        contentDescs = new String[]{
                "巩俐不低俗，我就不能低俗",
                "扑树又回来啦！再唱经典老歌引万人大合唱",
                "揭秘北京电影如何升级",
                "乐视网TV版大派送",
                "热血屌丝的反杀"
        };

        // 初始化要展示的5个ImageView
        imageViewList = new ArrayList<ImageView>();

        ImageView imageView;
        View pointView;
        LinearLayout.LayoutParams layoutParams;
        for (int i = 0; i < imageResIds.length; i++) {
            // 初始化要显示的图片对象
            imageView = new ImageView(this);//this 是指在当前的activity之中建立一个ImageView对象
            //自定义的ImageView建立一个自定义的的背景
            imageView.setBackgroundResource(imageResIds[i]);
            imageViewList.add(imageView);

            ///加载小白点的资源的步骤1、定义一个view 组件，设置背景资源，设置属性的匡高，

            // 加小白点, 指示器
            pointView = new View(this);
            pointView.setBackgroundResource(R.drawable.ic_launcher_background);
            //定义一个普通的布局的属性
            layoutParams = new LinearLayout.LayoutParams(5, 5);
            if (i != 0)
                //设置每两个小圆点点的距离
                layoutParams.leftMargin = 10;
            // 设置默认所有都不可用 目的是在更新适配器时候的进行使用
            pointView.setEnabled(true);
            ll_point_container.addView(pointView, layoutParams);
        }
    }

    private void initAdapter() {
        ll_point_container.getChildAt(0).setEnabled(true);
        tv_desc.setText(contentDescs[0]);
        previousSelectedPosition = 0;

        // 设置适配器
        viewPager.setAdapter(new LocalBestActivity.MyAdapter());

        // 默认设置到中间的某个位置
        int pos = Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2 % imageViewList.size());
        // 2147483647 / 2 = 1073741823 - (1073741823 % 5)
        viewPager.setCurrentItem(5000000); // 设置到某个位置
    }

    class MyAdapter extends PagerAdapter {

        public int getCount() {
            return Integer.MAX_VALUE;
        }

        // 3. 指定复用的判断逻辑, 固定写法
        public boolean isViewFromObject(View view, Object object) {
//          System.out.println("isViewFromObject: "+(view == object));
            // 当划到新的条目, 又返回来, view是否可以被复用.
            // 返回判断规则
            return view == object;
        }

        // 1. 返回要显示的条目内容, 创建条目
        //创建条目对象。
        public Object instantiateItem(ViewGroup container, int position) {
            System.out.println("instantiateItem初始化: " + position);
            // container: 容器: ViewPager
            // position: 当前要显示条目的位置 0 -> 4

//          newPosition = position % 5
            //指定是哪一个条目的位置
            int newPosition = position % imageViewList.size();
            //从图片集之中提取出来加入容器
            ImageView imageView = imageViewList.get(newPosition);
            // a. 把View对象添加到container中
            container.addView(imageView);
            // b. 把View对象返回给框架, 适配器
            return imageView; // 必须重写, 否则报异常
        }

        // 2. 销毁条目
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // object 要销毁的对象
            System.out.println("destroyItem销毁: " + position);
            container.removeView((View) object);
        }
    }

    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        // 滚动时调用
    }

    public void onPageSelected(int position) {
        // 新的条目被选中时调用
        System.out.println("onPageSelected: " + position);
        int newPosition = position % imageViewList.size();

        //设置文本
        tv_desc.setText(contentDescs[newPosition]);

//      for (int i = 0; i < ll_point_container.getChildCount(); i++) {
//          View childAt = ll_point_container.getChildAt(position);
//          childAt.setEnabled(position == i);
//      }
        // 把之前的禁用, 把最新的启用, 更新指示器
        ll_point_container.getChildAt(previousSelectedPosition).setEnabled(false);
        ll_point_container.getChildAt(newPosition).setEnabled(true);

        // 记录之前的位置
        previousSelectedPosition = newPosition;

    }

    public void onPageScrollStateChanged(int state) {
        // 滚动状态变化时调用
    }
}
